<template>
  <div>
    <div v-permission="['settle:pre-sheet:query']">
      <page-wrapper content-full-height fixed-height>
        <!-- 数据列表 -->
        <vxe-grid
          id="SettlePreSheet"
          ref="grid"
          resizable
          show-overflow
          highlight-hover-row
          keep-source
          row-id="id"
          :proxy-config="proxyConfig"
          :columns="tableColumn"
          :toolbar-config="toolbarConfig"
          :custom-config="{}"
          :pager-config="{}"
          :loading="loading"
          height="auto"
        >
          <template #form>
            <j-border>
              <j-form @collapse="$refs.grid.refreshColumn()" class="formstyle">
                <div class="search-container">
                  <div class="search-row">
                    <j-form-item label="商品名称">
                      <a-input
                        v-model:value="searchFormData.name"
                        allow-clear
                        placeholder="请输入商品名称"
                      />
                    </j-form-item>
                    <div class="empty-space"></div>
                  </div>
                  <div class="search-row">
                    <j-form-item label="商品编号">
                      <a-select v-model:value="searchFormData.code" placeholder="请选择商品编号">
                        <a-select-option value="1">001</a-select-option>
                        <a-select-option value="2">002</a-select-option>
                      </a-select>
                    </j-form-item>
                    <a-button
                      type="primary"
                      :icon="h(SearchOutlined)"
                      @click="search"
                      class="search-btn"
                    >
                      查询
                    </a-button>
                  </div>
                </div>
              </j-form>
            </j-border>
          </template>
          <!-- 工具栏 -->
          <template #toolbar_buttons>
            <a-space>
              <a-button
                v-permission="['settle:pre-sheet:add']"
                type="primary"
                :icon="h(PlusOutlined)"
                @click="$router.push('/settle/supplier/pre-sheet/add')"
                >新增</a-button
              >
            </a-space>
          </template>

          <!-- 操作 列自定义内容 -->
          <template #action_default="{ row }">
            <table-action outside :actions="createActions(row)" />
          </template>
        </vxe-grid>
      </page-wrapper>

      <!-- 查看窗口 -->
      <!-- <detail :id="id" ref="viewDialog" /> -->

      <approve-refuse ref="approveRefuseDialog" @confirm="doApproveRefuse" />
    </div>
  </div>
</template>

<script>
import { h, defineComponent } from 'vue';
// import Detail from './detail.vue';
import ApproveRefuse from '@/components/ApproveRefuse';
import moment from 'moment';
import {
  SearchOutlined,
  PlusOutlined,
  CheckOutlined,
  CloseOutlined,
  DeleteOutlined,
  DownloadOutlined,
} from '@ant-design/icons-vue';
import * as api from '@/api/settle/pre';

export default defineComponent({
  name: 'SettlePreSheet',
  components: {
    // Detail,
    ApproveRefuse,
  },
  setup() {
    return {
      h,
      SearchOutlined,
      PlusOutlined,
      CheckOutlined,
      CloseOutlined,
      DeleteOutlined,
      DownloadOutlined,
    };
  },
  data() {
    return {
      loading: false,
      // 当前行数据
      id: '',
      // 查询列表的查询条件
      searchFormData: {
        code: '',
        supplierId: '',
        createBy: '',
        createStartTime: this.$utils.formatDateTime(
          this.$utils.getDateTimeWithMinTime(moment().subtract(1, 'M')),
        ),
        createEndTime: this.$utils.formatDateTime(this.$utils.getDateTimeWithMaxTime(moment())),
        approveBy: '',
        approveStartTime: '',
        approveEndTime: '',
        status: undefined,
      },
      // 工具栏配置
      toolbarConfig: {
        // 自定义左侧工具栏
        slots: {
          buttons: 'toolbar_buttons',
        },
      },
      // 列表数据配置
      tableColumn: [
        { type: 'checkbox', width: 45 },
        { field: 'code', title: '单据号', width: 180, sortable: true },
        { field: 'supplierCode', title: '供应商编号', width: 100 },
        { field: 'supplierName', title: '供应商名称', width: 120 },
        { field: 'totalAmount', title: '单据总金额', align: 'right', width: 100 },
        { field: 'createTime', title: '操作时间', width: 170, sortable: true },
        { field: 'createBy', title: '操作人', width: 100 },
        {
          field: 'status',
          title: '状态',
          width: 100,
          formatter: ({ cellValue }) => {
            return this.$enums.SETTLE_PRE_SHEET_STATUS.getDesc(cellValue);
          },
        },
        { field: 'approveTime', title: '审核时间', width: 170, sortable: true },
        { field: 'approveBy', title: '审核人', width: 100 },
        {
          field: 'settleStatus',
          title: '结算状态',
          width: 100,
          formatter: ({ cellValue }) => {
            return this.$enums.SETTLE_STATUS.getDesc(cellValue);
          },
        },
        { field: 'description', title: '备注', width: 200 },
        { title: '操作', width: 200, fixed: 'right', slots: { default: 'action_default' } },
      ],
      // 请求接口配置
      proxyConfig: {
        props: {
          // 响应结果列表字段
          result: 'datas',
          // 响应结果总条数字段
          total: 'totalCount',
        },
        ajax: {
          // 查询接口
          query: ({ page, sorts }) => {
            return api.query(this.buildQueryParams(page, sorts));
          },
        },
      },
    };
  },
  created() {},
  methods: {
    // 列表发生查询时的事件
    search() {
      this.$refs.grid.commitProxy('reload');
    },
    // 查询前构建查询参数结构
    buildQueryParams(page, sorts) {
      return {
        ...this.$utils.buildSortPageVo(page, sorts),
        ...this.buildSearchFormData(),
      };
    },
    // 查询前构建具体的查询参数
    buildSearchFormData() {
      return {
        code: this.searchFormData.code,
        supplierId: this.searchFormData.supplierId,
        createBy: this.searchFormData.createBy,
        createStartTime: this.searchFormData.createStartTime,
        createEndTime: this.searchFormData.createEndTime,
        approveBy: this.searchFormData.approveBy,
        approveStartTime: this.searchFormData.approveStartTime,
        approveEndTime: this.searchFormData.approveEndTime,
        status: this.searchFormData.status,
        settleStatus: this.searchFormData.settleStatus,
      };
    },
    // 删除订单
    deleteOrder(row) {
      this.$msg.createConfirm('对选中的预付款单执行删除操作？').then(() => {
        this.loading = true;
        api
          .deleteById(row.id)
          .then(() => {
            this.$msg.createSuccess('删除成功！');
            this.search();
          })
          .finally(() => {
            this.loading = false;
          });
      });
    },
    // 批量删除
    batchDelete() {
      const records = this.$refs.grid.getCheckboxRecords();
      if (this.$utils.isEmpty(records)) {
        this.$msg.createError('请选择要执行操作的预付款单！');
        return;
      }

      for (let i = 0; i < records.length; i++) {
        if (this.$enums.SETTLE_PRE_SHEET_STATUS.APPROVE_PASS.equalsCode(records[i].status)) {
          this.$msg.createError('第' + (i + 1) + '个预付款单已审核通过，不允许执行删除操作！');
          return;
        }
      }

      this.$msg.createConfirm('对选中的预付款单执行批量删除操作？').then((valid) => {
        if (valid) {
          this.loading = true;
          api
            .deleteByIds(records.map((item) => item.id))
            .then(() => {
              this.$msg.createSuccess('删除成功！');
              this.search();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    // 批量审核通过
    batchApprovePass() {
      const records = this.$refs.grid.getCheckboxRecords();
      if (this.$utils.isEmpty(records)) {
        this.$msg.createError('请选择要执行操作的预付款单！');
        return;
      }

      for (let i = 0; i < records.length; i++) {
        if (this.$enums.SETTLE_PRE_SHEET_STATUS.APPROVE_PASS.equalsCode(records[i].status)) {
          this.$msg.createError('第' + (i + 1) + '个预付款单已审核通过，不允许继续执行审核！');
          return;
        }
      }

      this.$msg.createConfirm('对选中的预付款单执行审核通过操作？').then((valid) => {
        if (valid) {
          this.loading = true;
          api
            .batchApprovePass({
              ids: records.map((item) => item.id),
            })
            .then(() => {
              this.$msg.createSuccess('审核通过！');
              this.search();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    // 批量审核拒绝
    batchApproveRefuse() {
      const records = this.$refs.grid.getCheckboxRecords();
      if (this.$utils.isEmpty(records)) {
        this.$msg.createError('请选择要执行操作的预付款单！');
        return;
      }

      for (let i = 0; i < records.length; i++) {
        if (this.$enums.SETTLE_PRE_SHEET_STATUS.APPROVE_PASS.equalsCode(records[i].status)) {
          this.$msg.createError('第' + (i + 1) + '个预付款单已审核通过，不允许继续执行审核！');
          return;
        }

        if (this.$enums.SETTLE_PRE_SHEET_STATUS.APPROVE_REFUSE.equalsCode(records[i].status)) {
          this.$msg.createError('第' + (i + 1) + '个预付款单已审核拒绝，不允许继续执行审核！');
          return;
        }
      }

      this.$refs.approveRefuseDialog.openDialog();
    },
    doApproveRefuse(reason) {
      const records = this.$refs.grid.getCheckboxRecords();

      this.loading = true;
      api
        .batchApproveRefuse({
          ids: records.map((item) => item.id),
          refuseReason: reason,
        })
        .then(() => {
          this.$msg.createSuccess('审核拒绝！');
          this.search();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    exportList() {
      this.loading = true;
      api
        .exportList(this.buildQueryParams({}))
        .then(() => {
          this.$msg.createSuccessTip('导出成功！');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    createActions(row) {
      return [
        {
          label: '查看',
          onClick: () => {
            this.id = row.id;
            this.$nextTick(() => this.$refs.viewDialog.openDialog());
          },
        },
        {
          permission: ['settle:pre-sheet:approve'],
          label: '审核',
          ifShow: () => {
            return (
              this.$enums.SETTLE_PRE_SHEET_STATUS.CREATED.equalsCode(row.status) ||
              this.$enums.SETTLE_PRE_SHEET_STATUS.APPROVE_REFUSE.equalsCode(row.status)
            );
          },
          onClick: () => {
            this.$router.push('/settle/supplier/pre-sheet/approve/' + row.id);
          },
        },
        {
          permission: ['settle:pre-sheet:modify'],
          label: '修改',
          ifShow: () => {
            return (
              this.$enums.SETTLE_PRE_SHEET_STATUS.CREATED.equalsCode(row.status) ||
              this.$enums.SETTLE_PRE_SHEET_STATUS.APPROVE_REFUSE.equalsCode(row.status)
            );
          },
          onClick: () => {
            this.$router.push('/settle/supplier/pre-sheet/modify/' + row.id);
          },
        },
        {
          permission: ['settle:pre-sheet:delete'],
          label: '删除',
          color: 'error',
          ifShow: () => {
            return (
              this.$enums.SETTLE_PRE_SHEET_STATUS.CREATED.equalsCode(row.status) ||
              this.$enums.SETTLE_PRE_SHEET_STATUS.APPROVE_REFUSE.equalsCode(row.status)
            );
          },
          onClick: () => {
            this.deleteOrder(row);
          },
        },
      ];
    },
  },
});
</script>
<style lang="less" scoped>
.formstyle {
  .search-container {
    display: flex;
    flex-direction: column;
    gap: 16px;
    width: 100%;
  }

  .search-row {
    display: flex;
    gap: 16px;
    align-items: flex-start;

    :deep(.j-form-item) {
      width: 300px; // 设置固定宽度
      margin-bottom: 0;
    }

    .empty-space {
      width: 300px; // 与表单项宽度相同
    }

    .search-btn {
      margin-top: 4px;
      width: 80px; // 设置按钮宽度
    }
  }
}

// 隐藏工具栏中的查询按钮
:deep(.toolbar_buttons) {
  .ant-btn-primary:first-child {
    display: none;
  }
}
</style>
